/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;

import common.APComputer;
import common.Fields;
import common.PositionTuple;
import common.FWDAPSet;

public class NetworkMPLSAP extends NetworkAP{

    /**
     * 
     */
    private static final long serialVersionUID = 3865879802926611461L;

    ArrayList<String[]> mpls_paths;

    int max_tunnel_hop;
    int total_tunnel_hop;
    int iter_num;
    int used_tunnel_num;

    public NetworkMPLSAP(String name) throws IOException {
        super(name);
    }

    public void read_tunnels_from_file(String tunnel_file_name) throws IOException
    {
        mpls_paths = get_tunnels(tunnel_file_name);
        //Collections.shuffle(mpls_paths);
    }

    public static ArrayList<String[]> get_tunnels(String tunnel_file_name)
    {
        ArrayList<String[]> paths = new ArrayList<String[]> ();

        try{

            FileInputStream fis = new FileInputStream(new File(tunnel_file_name));
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            String line = null;
            while ((line = br.readLine()) != null) {

                String[] path_info = line.split(" ");

                paths.add(path_info);

                System.out.println(path_info[0]+"->"+path_info[path_info.length-1]);

            }

            br.close();

        }catch(Exception e)
        {
            e.printStackTrace();
        }

        return paths;
    }

    public void add_mpls_paths()
    {

        max_tunnel_hop = 0;
        total_tunnel_hop = 0;

        if(used_tunnel_num > mpls_paths.size())
        {
            used_tunnel_num = mpls_paths.size();
        }

        ini_mpls();
        for(int i = 0; i < used_tunnel_num; i ++)
        {
            String[] tunnel = mpls_paths.get(i);
            int tunnel_hop = tunnel.length/2-1;
            total_tunnel_hop += tunnel_hop;
            if(max_tunnel_hop < tunnel_hop)
            {
                max_tunnel_hop = tunnel_hop;
            }
            add_mpls_path(tunnel);
        }
    }

    public void add_one_tunnel_update(int tunnel_id)
    {
        String[] tunnel = mpls_paths.get(tunnel_id);
        used_tunnel_num ++;
        int tunnel_hop = tunnel.length/2-1;
        total_tunnel_hop += tunnel_hop;
        if(max_tunnel_hop < tunnel_hop)
        {
            max_tunnel_hop = tunnel_hop;
        }
        add_mpls_path_update(tunnel);
    }

    public void ap_first_iter()
    {

        long t1 = System.currentTimeMillis();
        // add not mplsLabelBit

        for(Box b : boxes.values())
        {
            if(b instanceof Device)
            {
                Device d = (Device) b;
                for (String port : d.fwbdds.keySet())
                {
                    int original_pkts = d.fwbdds.get(port);
                    int decor_pkts = bddengine.set_field_bit(Fields.mpls_label, original_pkts, false);
                    d.fwbdds.put(port, decor_pkts);
                }
            }
        }

        HashSet<Integer> predicates = new HashSet<Integer>();
        for(Box b : boxes.values())
        {
            if(b instanceof Device)
                predicates.addAll(((Device) b).fwbdds.values());
        }
        predicates.add(bddengine.get_all_mpls_pkts());
        apc = new APComputer(bddengine);

        int size = apc.addPredicates(new ArrayList<Integer>(predicates));
        long t2 = System.currentTimeMillis();

        ap_times[0] = t2-t1;

        System.out.println("computing atomic predicates for filters takes "+ap_times[0]+" ms");
        System.out.println(size + " atomic predicates");      
    }

    public void one_iter(ArrayList<MPLSTable> tables)
    {
        //Collections.shuffle(tables);
        ArrayList<Integer> transformedPredicates = new ArrayList<Integer> ();
        for(MPLSTable one_table : tables)
        {
            one_table.updatePredicatesMap(apc);
            transformedPredicates.addAll(one_table.get_all_changed_predicates());
        }

        //System.out.println(tables.size());
        //System.out.println(transformedPredicates.size());

        int size = apc.addPredicates(transformedPredicates);
        //System.out.println(size + " atomic predicates.");
    }
    
    public void one_iter2(ArrayList<MPLSTable> tables)
    {
        //Collections.shuffle(tables);
        ArrayList<Integer> transformedPredicates = new ArrayList<Integer> ();
        for(MPLSTable one_table : tables)
        {
            one_table.updatePredicatesMap(apc);
            transformedPredicates.addAll(one_table.get_all_changed_predicates());
        }

        //System.out.println(tables.size());
        //System.out.println(transformedPredicates.size());

        apc.update_a(transformedPredicates);
        //System.out.println(size + " atomic predicates.");
    }

    public void one_iter(ArrayList<MPLSTable> tables, ArrayList<IPinIP> ip_tunnels, ArrayList<NATBox> nats)
    {
        ArrayList<Integer> transformedPredicates = new ArrayList<Integer> ();
        for(MPLSTable one_table : tables)
        {
            one_table.updatePredicatesMap(apc);
            transformedPredicates.addAll(one_table.get_all_changed_predicates());
        }
        
        for(IPinIP one_tunnel : ip_tunnels)
        {
            one_tunnel.updatePredicatesMap(apc);
            transformedPredicates.addAll(one_tunnel.predicatesMap.values());
        }
        


        for(NATBox nat : nats)
        {
            nat.updateTranslatedPredicates(apc);
        }

        for(NATBox nat: nats)
        {
            for(int i : nat.translatedPredicates_in.values())
            {
                transformedPredicates.add(i);
            }
            for(int i : nat.translatedPredicates_out.values())
            {
                transformedPredicates.add(i);
            }
        }

        //System.out.println(tables.size());
        //System.out.println(transformedPredicates.size());

        int size = apc.addPredicates(transformedPredicates);
        //System.out.println(size + " atomic predicates.");
    }

    public void one_iter_update(ArrayList<MPLSTable> tables)
    {
        ArrayList<Integer> transformedPredicates = new ArrayList<Integer> ();
        for(MPLSTable one_table : tables)
        {
            one_table.updatePredicatesMap(apc);
            transformedPredicates.addAll(one_table.get_all_changed_predicates());
        }

        //System.out.println(tables.size());
        //System.out.println(transformedPredicates.size());

        apc.update_a(transformedPredicates);
        //System.out.println(size + " atomic predicates.");
    }

    /**
     * compute atomic predicates only. Not ready for computing reachability
     * @param nat_num
     * @param ip_tunnel_num
     * @param mpls_num
     */
    public void ap_all(int nat_num, int ip_tunnel_num, int mpls_num)
    {
        // first, add tunnels
        //MPLS
        used_tunnel_num = mpls_num;
        add_mpls_paths();
        convert_mpls_bdd();

        // IPinIP
        ArrayList<String[]> ip_tunnels = NetworkIPinIPAP.read_tunnel_file("i2_ipinip_tunnels");
        ini_IPinIP();


        for(int i = 0; i < ip_tunnel_num; i ++)
        {
            String[] tunnel = ip_tunnels.get(i);
            add_ipinip_tunnel(tunnel[0], tunnel[1], tunnel[2]);
        }

        // NAT
        //ArrayList<NATBox> nats = new ArrayList<NATBox>();
        //nats.add(add_nat("chic"));
        ArrayList<NATBox> nats = add_nat(nat_num);

        ap_first_iter();

        ArrayList<MPLSTable> tables = new ArrayList<MPLSTable> ();
        for(Box b : boxes.values())
        {
            if(b instanceof Device)
            {
                Device d = (Device) b;
                if(d.mpls_table != null)
                {
                    tables.add(d.mpls_table);
                }
            }
        }

        ArrayList<IPinIP> tunnels = new ArrayList<IPinIP> ();
        for(Box b : boxes.values())
        {
            if(b instanceof Device)
            {
                Device d = (Device) b;
                if(d.ip_in_ip != null)
                {
                    tunnels.add(d.ip_in_ip);
                }
            }
        }

        int old_size = apc.getAPNum();

        //
        long t1 = System.currentTimeMillis();
        iter_num = 0;
        while(true)
        {
            iter_num ++;
            one_iter(tables, tunnels, nats);
            int new_size = apc.getAPNum();
            if(new_size == old_size)
            {
                break;
            }else
            {
                old_size = new_size;
            }
        }
        long t2 = System.currentTimeMillis();
        ap_times[1] = t2 - t1;
        System.out.println(iter_num + " iterations.");

        System.out.println(apc.getAPNum() + " atomic predicates.");
        System.out.println(ap_times[1]+" ms to compute atomic predicates for MPLS tunnels");

    }
    
    /**
     * compute atomic predicates only. Not ready for computing reachability
     * experiments
     */
    public void ap_all2()
    {
        // first, add tunnels
        //MPLS
        ini_mpls();
        ini_IPinIP();
        
        add_multiple_transformers();

        convert_mpls_bdd();        

        // NAT
        ArrayList<NATBox> nats = new ArrayList<NATBox>();
        for(Box b : boxes.values())
        {
            if(b instanceof NATBox)
            {
                nats.add((NATBox) b);
            }
        }

        ap_first_iter();

        ArrayList<MPLSTable> tables = new ArrayList<MPLSTable> ();
        for(Box b : boxes.values())
        {
            if(b instanceof Device)
            {
                Device d = (Device) b;
                if(d.mpls_table != null)
                {
                    tables.add(d.mpls_table);
                }
            }
        }

        ArrayList<IPinIP> tunnels = new ArrayList<IPinIP> ();
        for(Box b : boxes.values())
        {
            if(b instanceof Device)
            {
                Device d = (Device) b;
                if(d.ip_in_ip != null)
                {
                    tunnels.add(d.ip_in_ip);
                }
            }
        }

        int old_size = apc.getAPNum();

        //
        long t1 = System.currentTimeMillis();
        iter_num = 0;
        while(true)
        {
            iter_num ++;
            one_iter(tables, tunnels, nats);
            int new_size = apc.getAPNum();
            if(new_size == old_size)
            {
                break;
            }else
            {
                old_size = new_size;
            }
        }
        long t2 = System.currentTimeMillis();
        ap_times[1] = t2 - t1;
        System.out.println(iter_num + " iterations.");

        System.out.println(apc.getAPNum() + " atomic predicates.");
        System.out.println(ap_times[1]+" ms to compute atomic predicates for MPLS tunnels");

    }

    public void compute_ap_mpls(ArrayList<MPLSTable> tables)
    {
        int old_size = apc.getAPNum();

        if(used_tunnel_num > 0)
        {
            iter_num = 0;
            while(true)
            {
                iter_num ++;
                one_iter2(tables);
                int new_size = apc.getAPNum();
                if(new_size == old_size)
                {
                    break;
                }else
                {
                    old_size = new_size;
                }
            }
        }

    }

    public void ap_mpls(int tunnel_num)
    {
        // first, add tunnels
        used_tunnel_num = tunnel_num;
        add_mpls_paths();

        convert_mpls_bdd();

        ap_first_iter();

        ArrayList<MPLSTable> tables = new ArrayList<MPLSTable> ();
        for(Box b : boxes.values())
        {
            Device d = (Device) b;
            if(d.mpls_table != null)
            {
                tables.add(d.mpls_table);
            }
        }

        int old_size = apc.getAPNum();

        if(used_tunnel_num > 0)
        {
            long t1 = System.currentTimeMillis();
            iter_num = 0;
            while(true)
            {
                iter_num ++;
                one_iter(tables);
                int new_size = apc.getAPNum();
                if(new_size == old_size)
                {
                    break;
                }else
                {
                    old_size = new_size;
                }
            }
            long t2 = System.currentTimeMillis();
            ap_times[1] = t2 - t1;
            System.out.println(iter_num + " iterations.");
        }else
        {
            ap_times[1] = 0;
        }

        System.out.println(apc.getAPNum() + " atomic predicates.");
        System.out.println(ap_times[1]+" ms to compute atomic predicates for MPLS tunnels");

        /*
         *  set AP set for mpls pkts and non mpls pkts in Device class;
         *  implement setaps for MPLSTable
         */      
        apc.computeExpressions();
        FWDAPSet.setUniverse(apc.getAllAP());
        Device.set_MPLS_ap_pkts(apc);

        for(Box b : boxes.values())
        {
            b.setaps(apc);
        }


        for(MPLSTable one_table : tables)
        {
            one_table.setaps(apc);
        }


    }

    public void ap_mpls_update()
    {
        int tunnel_num = mpls_paths.size();
        ap_mpls(tunnel_num-1);

        long t1 = System.currentTimeMillis();
        add_one_tunnel_update(tunnel_num-1);


        ArrayList<MPLSTable> tables = new ArrayList<MPLSTable> ();
        for(Box b : boxes.values())
        {
            Device d = (Device) b;
            if(d.mpls_table != null)
            {
                tables.add(d.mpls_table);
            }
        }

        int old_size = apc.getAPNum();

        iter_num = 0;
        while(true)
        {
            iter_num ++;
            one_iter_update(tables);
            int new_size = apc.getAPNum();
            if(new_size == old_size)
            {
                break;
            }else
            {
                old_size = new_size;
            }
        }
        long t2 = System.currentTimeMillis();
        ap_times[1] = t2 - t1;
        System.out.println(iter_num + " iterations.");


        System.out.println(apc.getAPNum() + " atomic predicates.");
        System.out.println(ap_times[1]+" ms to compute atomic predicates for MPLS tunnels");

        /*
         *  set AP set for mpls pkts and non mpls pkts in Device class;
         *  implement setaps for MPLSTable
         */      
        FWDAPSet.setUniverse(apc.getAllAP());
        Device.set_MPLS_ap_pkts(apc);

        for(Box b : boxes.values())
        {
            b.setaps(apc);
        }


        for(MPLSTable one_table : tables)
        {
            one_table.setaps(apc);
        }


    }

    public void log(boolean append)
    {
        String filename = "i2_mpls_ap_states";
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, append)));
            out.println(apc.getAPNum() + " " + used_tunnel_num +" " + max_tunnel_hop + 
                    " " + iter_num + " " + total_tunnel_hop);
            out.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public double compute_trees()
    {
        HashSet<PositionTuple> pts = getallactiveports();
        FWDAPSet non_mpls_pkts = bddengine.get_nonmpls_pkts_ap(apc);

        return StateTransferAP.compute_trees(this, pts, non_mpls_pkts, false);
    }
    
    public void update_port_predicate_mpls()
    {
        ArrayList<int[]> updates = new ArrayList<int[]> ();
        used_tunnel_num = 28;
        add_mpls_paths();

        convert_mpls_bdd();

        HashSet<Integer> predicates = new HashSet<Integer>();
        for(Box b : boxes.values())
        {
            int count = 0;
            // for each router, pick two port predicates
            int[] update = new int[2];

            if(b instanceof Device)
            {
                int size = ((Device) b).fwbdds.size();
                int[] picks = randPicksRange(1, size);
                
                for(int port_predicate : ((Device) b).fwbdds.values())
                {
                    count ++;
                    if(count == picks[0])
                    {
                        update[0] = port_predicate;
                    }else{
                        if(count == picks[1])
                        {
                            update[1] = port_predicate;
                            updates.add(update);
                        }
                        predicates.add(port_predicate);
                    }
                }
            }
        }
        
        APComputer apc = new APComputer(bddengine);
        this.apc = apc;
        
        ArrayList<MPLSTable> tables = new ArrayList<MPLSTable> ();
        for(Box b : boxes.values())
        {
            Device d = (Device) b;
            if(d.mpls_table != null)
            {
                tables.add(d.mpls_table);
            }
        }

        int size = apc.addPredicates(new ArrayList<Integer>(predicates));
        apc.computeExpressions();
        compute_ap_mpls(tables);
       
                
        long update_time = 0;
        
        for(int[] update : updates)
        {
            long t1 = System.currentTimeMillis();

            apc.update_r(update[1]);
            apc.update_a(update[0]);

            compute_ap_mpls(tables);;
            long t2 = System.currentTimeMillis();

            update_time += t2-t1;
            
            System.out.println(t2-t1);
        }
        
        System.out.println("update time: " + (1.0*update_time/updates.size())+ " ms");

    }

    public static void main(String[] args) throws IOException
    {
        NetworkMPLSAP net_mpls_ap = new NetworkMPLSAP("i2");

        /*
        String[] path_info = {"losa", "43000", "hous", 
                "43001", "atla", "43002", "wash", "3", "chic", "salt"};

        net_mpls_ap.mpls_paths.add(path_info);
        path_info = new String[]{"losa", "46000", "hous", "46001", 
                        "atla", "3", "chic", "salt"};
        net_mpls_ap.mpls_paths.add(path_info);
         */
        net_mpls_ap.read_tunnels_from_file("i2_unique_tunnels");
        net_mpls_ap.update_port_predicate_mpls();
        //net_mpls_ap.ap_mpls(28);
        //net_mpls_ap.ap_mpls_update();
        //net_mpls_ap.log(true);
        //net_mpls_ap.ap_all(0, 0, 2);
        //net_mpls_ap.ap_all2();
    }

}
